use anyhow::Context;
use serde::{Deserialize, Serialize};

use crate::errors::FreighterError;

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct GithubLatestRelease {
    pub tag_name: String,
}

pub async fn get_latest() -> Result<GithubLatestRelease, FreighterError> {
    let client = reqwest::Client::new();
    let resp = client
        .get("https://api.github.com/repos/rust-lang/rust/releases/latest")
        .header("User-Agent", format!("Freighter/{}", "0.0.1"))
        .send()
        .await
        .context("failed in sending request to target Url")?;

    let res = if resp.status().is_success() {
        resp.json::<GithubLatestRelease>()
            .await
            .context("failed to deserialize response as JSON")?
    } else {
        tracing::error!("github:user_info:err {:?}", resp.text().await.unwrap());
        GithubLatestRelease::default()
    };
    Ok(res)
}
